from ..libmoops import int_to_twos, twos_to_int

class alu(object):

    def __init__(self):
        self.overflow = 0

    def compute(self, aluOp, A, B):
        self.overflow = 0
        if (aluOp == 0b0000): #and
            self.result = A & B
        elif (aluOp == 0b0001): #or
            self.result = A | B
        elif (aluOp == 0b0010): #add
            amount = twos_to_int(A) + twos_to_int(B)
            print("!!!!!!!!!! amount" + str(amount))
            if(amount >= 0x1000000): #did overflow happen?
                print("OVERFLOW ALERT!")
                self.overflow = 1
            self.result = int_to_twos(amount)
        elif (aluOp == 0b0011): #addu
            amount = A + B
            self.result = 0xFFFFFFFF & amount
        elif (aluOp == 0b0110): #subtract
            amount = twos_to_int(A) - twos_to_int(B)
            if(amount < -0x1000000): #did overflow happen?
                print("OVERFLOW ALERT!")
                self.overflow = 1
            self.result = int_to_twos(amount)
        elif (aluOp == 0b1011): #subu
            amount = A - B
            self.result = 0xFFFFFFFF & amount
        elif (aluOp == 0b0111): #slt
            if (twos_to_int(A) < twos_to_int(B)):
                self.result = 1 
            else:
                self.result = 0
        elif (aluOp == 0b1000): #sll
            self.result = 0xFFFFFFFF & (B << A)
        elif (aluOp == 0b1001): #srl
            self.result = 0xFFFFFFFF & (B >> A)
        elif (aluOp == 0b1111): #sra
            A1 = 0xFFFFFFFF & ( B << (32 - A) )
            A2 = 0xFFFFFFFF & ( B >> A )
            self.result = A1 | A2
        else:
            self.result = 0
    ##todo,overflow detect

    def getResults(self):
        return self.result

    def getZero(self):
        if(self.result == 0):
            return 1
        else:
            return 0
